<?php

namespace app\middleware;

use app\consts\Keywords;
use Webman\Http\Request;
use Webman\Http\Response;
use Webman\MiddlewareInterface;

class Prequest implements MiddlewareInterface
{
    public function process(Request $request, callable $handler) : Response
    {
        //多语言处理
        {
            $lang = $request->header("Locale");
            //设置本次请求的语言
            $lang || $lang = config("translation.locale");
            $request->{Keywords::LANG} = $lang;
            //设置多语言
            locale($lang);
        }

        //请求id附加
        {
            $request_id = $request->header("X-Request-Id");
            $request_id || $request_id = uniqid();
            $request->{Keywords::REQUEST_ID} = $request_id;
        }

        $response =  $handler($request);

        $response->withHeaders([
            "X-Request-Id" => $request_id
        ]);

        return $response;
    }
}